package com.school.controller.common;

import com.itextpdf.text.DocumentException;
import com.school.dto.SimpleSign;
import com.school.exception.UserNotFoundException;
import com.school.model.Pics;
import com.school.model.Sign;
import com.school.model.User;
import com.school.service.impl.PicsServiceImpl;
import com.school.service.impl.SignServiceImpl;
import com.school.service.impl.UserServiceImpl;
import com.school.utils.FileEnum;
import com.school.utils.FileUtil;
import com.school.utils.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

@Api(value = "签约证书下载", tags = {"签约证书下载"})
@RestController
@RequestMapping("/api/admin/certification")
public class CertificationDownloadController {
    @Autowired
    private SignServiceImpl signService;

    @Autowired
    FileUtil fileUtil;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    private PicsServiceImpl picsService;


    @GetMapping("/download/{signId}")
    @PreAuthorize("hasAnyRole('USER','ADMINISTRATOR')")
    @ApiOperation(value = "下载签约证书", notes = "下载签约证书")
    public String downloadCertification(@PathVariable("signId") Integer signId,
                                        HttpServletResponse response) throws UserNotFoundException {
        Sign sign = signService.queryById(signId);
        Assert.notNull(sign, "该则签约id不存在！");
        return fileUtil.downloadCertification(response, sign);
    }

    @GetMapping("/download2/{signId}")
    //下载签约证书 pdf,比较漂亮的那个
//    @PreAuthorize("hasAnyRole('USER','ADMINISTRATOR')")
    @ApiOperation(value = "下载签约证书2", notes = "下载签约证书2")
    public String downloadCertification2(@PathVariable("signId") Integer signId,
                                         HttpServletResponse response) throws UserNotFoundException, IOException, DocumentException {

        Sign sign = signService.queryById(signId);
        Assert.notNull(sign, "该则签约id不存在！");
        fileUtil.downloadCertification2(response, sign);
        return ResponseUtil.build(HttpStatus.BAD_REQUEST.value(), "下载签约证书成功！");
    }

    /**
     * 用户专门定制的logo
     *
     * @param signId
     * @param response
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    @GetMapping("/download3/{signId}")
    @ApiOperation(value = "下载签约证书2-用户定制过的logo", notes = "用户定制过的logo")
//    @PreAuthorize("hasAnyRole('ADMINISTRATOR')")
    public Object downloadResizedLogo(@PathVariable("signId") Integer signId,
                                      HttpServletResponse response) throws IOException, DocumentException {
        Sign sign = signService.queryById(signId);
        Assert.notNull(sign, "该则签约id不存在！");
        fileUtil.downloadCertification3(sign, response);
        return ResponseUtil.build(HttpStatus.OK.value(), "下载用户自定义的签约证书成功!");
    }

    @GetMapping("/downloadCertificationFake")
    @ApiOperation(value = "管理端下载预览的签约证书", notes = "管理端下载预览的签约证书")
//    @PreAuthorize("hasAnyRole('ADMINISTRATOR')")
    public Object resizeLogo(@RequestParam("userId") Integer userId,
                             @RequestParam(value = "offsetX", required = false, defaultValue = "0") Integer offsetX,
                             @RequestParam(value = "offsetY", required = false, defaultValue = "0") Integer offsetY,
                             @RequestParam(value = "width", required = false, defaultValue = "0") Integer width,
                             @RequestParam(value = "height", required = false, defaultValue = "0") Integer height,
                             HttpServletResponse response) throws IOException, DocumentException {
        fileUtil.downloadCertificationFake(userId, offsetX, offsetY, width, height, response);
        picsService.insertSelective(userId, FileEnum.LOGO.value(), offsetX, offsetY, width, height);
        return ResponseUtil.build(HttpStatus.OK.value(), "下载用户自定义的签约证书成功!");
    }

    @GetMapping("/allSignIds")
    @PreAuthorize("hasRole('ADMINISTRATOR')")
    public String allSignIds() {
        List<Sign> signs = signService.querySelective();
        List<SimpleSign> simpleSigns = new LinkedList<>();
        for (Sign sign : signs) {
            try {
                checkLogo(sign.getSignUserId());
                checkLogo(sign.getSignedUserId());
//                checkLogoAndSignature(sign.getSignUserId());
//                checkLogoAndSignature(sign.getSignedUserId());
            } catch (NullPointerException e) {
                System.out.println(e.getMessage());
                continue;
            }
            SimpleSign simpleSign = new SimpleSign();
            simpleSign.setSignId(sign.getId());
            Integer signUserId = sign.getSignUserId();
            User user = userService.queryById(signUserId, User.Column.id, User.Column.schoolName);
            simpleSign.setSignSchoolName(user.getSchoolName());
            Integer signedUserId = sign.getSignedUserId();
            User signedUser = userService.queryById(signedUserId, User.Column.id, User.Column.schoolName);
            simpleSign.setSignedSchoolName(signedUser.getSchoolName());
            simpleSigns.add(simpleSign);
        }
        return ResponseUtil.build(HttpStatus.OK.value(), "获取证书id成功！", simpleSigns);
    }

    private void checkLogo(Integer signUserId) {
        List<Pics> pics = picsService.querySelective(null, signUserId, FileEnum.LOGO.value());
        if (pics.size() == 0) {
            throw new NullPointerException("用户未上传logo！");
        }
    }
}
